package com.bstek.ureport.utils;

import cn.hutool.core.util.StrUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.HashSet;
import java.util.Set;

public class XmlUtils {

    public static String getParameter(String content) throws Exception{
        // 将 XML 字符串转换为 InputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes("UTF-8"));
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputStream);
        doc.getDocumentElement().normalize();
        // 获取所有 <parameter> 节点
        NodeList parameterList = doc.getElementsByTagName("parameter");
        // 遍历每个 <parameter> 节点
        StringBuffer strb = new StringBuffer();
        Set<String> setDistinct = new HashSet<>();
        for (int i = 0; i < parameterList.getLength(); i++) {
            Node parameterNode = parameterList.item(i);

            if (parameterNode.getNodeType() == Node.ELEMENT_NODE) {
                Element parameterElement = (Element) parameterNode;

                // 提取属性值
                String name = parameterElement.getAttribute("name");
                String defaultValue = parameterElement.getAttribute("default-value");
                if(StrUtil.isNotBlank(defaultValue)){
                    boolean add = setDistinct.add(name);
                    if(add){
                        strb.append("&").append(name).append("=").append(defaultValue);
                    }
                }
            }
        }
        return strb.toString();

    }
}
